<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/7/21
 * Time: 11:54
 */

namespace Api\Util;


class OpensslEncryptHelper
{

    /**
     * 解密字符串
     * @param string $data 字符串
     * @param string $key 加密key
     * @return string
     */
    public static function decryptWithOpenssl($data){
        //加上这是为了防止解析出错
        $data = str_replace(" ",'+',$data);
        $encodeParam = self::getEncodeParam();
        $data = base64_decode($data);
        $result = openssl_decrypt($data,"AES-128-CBC",$encodeParam['key'],OPENSSL_RAW_DATA,$encodeParam['iv']);
        return $result;
    }

    /**
     * 加密字符串
     * 参考网站： https://segmentfault.com/q/1010000009624263
     * @param string $data 字符串
     * @param string $key 加密key
     * @return string
     */
    public static function encryptWithOpenssl($data){

        $encodeParam = self::getEncodeParam();
//        echo base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
//        echo base64_encode(openssl_encrypt("123456","AES-128-CBC","1234567890123456",OPENSSL_RAW_DATA,"1234567890123456"));
//        $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, self::$iv);
//        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, "1234567890123456", pkcs7_pad("123456"), MCRYPT_MODE_CBC, "1234567890123456"));
        return base64_encode(openssl_encrypt($data,"AES-128-CBC",$encodeParam['key'],OPENSSL_RAW_DATA,$encodeParam['iv']));
    }


    function pkcs7_pad($str)
    {
        $len = mb_strlen($str, '8bit');
        $c = 16 - ($len % 16);
        $str .= str_repeat(chr($c), $c);
        return $str;
    }


    public static function getEncodeParam(){
        return  C('DATA_DECODE_KEY');
    }
}